package com.ltv.xiangqiplugin.views;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.GridLayout;
import java.util.Vector;

import javax.swing.DefaultListModel;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import com.ltv.xiangqiplugin.controllers.MoveListControl;
import com.ltv.xiangqiplugin.models.MoveStack;
import com.ltv.xiangqiplugin.models.MoveStackObserver;

public class MoveStackView extends JPanel implements MoveStackObserver {
	private static MoveStackView instance;
	
	String TAB = "    ";
	Font font = new Font("Arial", Font.PLAIN, 14);
	FontMetrics metrics;
	
	private JList listbox;
	private DefaultListModel model;
	
	private MoveStackView() {
		metrics = getFontMetrics(font);
		JScrollPane scrollingList;
		model = new DefaultListModel();
		
		for (String move : MoveStack.getInstance().getMoves()) {
			model.add(0, move);
		}
		
		listbox = new JList(model);
		// Only one item can be selected
		listbox.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION);
		listbox.setSelectedIndex(0);
		listbox.setFont(font);
		
		listbox.addListSelectionListener(MoveListControl.getInstance());
		
		scrollingList = new JScrollPane(listbox);
		
		scrollingList.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
		scrollingList.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		
		setLayout(new GridLayout(1, 1));
		add(scrollingList);
	}

	public static MoveStackView getInstance() {
		if (instance == null) {
			instance = new MoveStackView();
		}
		
		return instance;
	}

	@Override
	public void updated(boolean moveListChanged) {
		listbox.removeListSelectionListener(MoveListControl.getInstance());
		if (moveListChanged) {
			model.clear();
			
			int moveListSize = MoveStack.getInstance().getVnMoves().size();
			Vector<String> vnMoves = MoveStack.getInstance().getVnMoves();
			for (int i = 0; i < moveListSize; i++) {
				model.add(0, getDisplayedMove(vnMoves.get(i), moveListSize - i, moveListSize));
			}
		}
		listbox.setSelectedIndex(model.getSize() - 1 - MoveStack.getInstance().getIndex());
		listbox.addListSelectionListener(MoveListControl.getInstance());
	}
	
	private String getSpaces(int numSpace) {
		String ret = "";
		for (int i = 0; i < numSpace; i++) {
			ret += " ";
		}
		
		return ret;
	}
	
	private String getDisplayedMove(String move, int index, int maxIndex) {
		if (move.equals("start")) {
			return "Start";
		}
		
		if (index % 2 == 0) {
			String ret = index/2 + "." + TAB;
			
			while (metrics.stringWidth(ret) < 50) {
				ret += " ";
			}
			
			return ret + move;
		} else {
			String ret = getSpaces((index/2 + "." + TAB).length());
			while (metrics.stringWidth(ret) < 50) {
				ret += " ";
			}
			
			return ret + move;
		}
	}
}
